package algorithm.trie;
import java.util.TreeMap;

/**
 * @author bingo
 * @Description
 * @Date 2018/7/11
 */
public class Trie {

    public class Node{

        public  boolean isWord;

        public TreeMap<Character,Node> next;

        public Node(boolean isWord) {
            this.isWord = isWord;
            this.next = new TreeMap<>();
        }

        public Node() {
            this(false);
        }
    }

    private Node root;

    private Integer size;


    public Trie(){
        root = new Node();
        size = 0;
    }

    public void add(String  str){
        Node cur = root;
        for(int i=0;i<str.length();i++){
            char  c = str.charAt(i);
            if(cur.next.get(c)==null){
                cur.next.put(c,new Node());
            }
            cur = cur.next.get(c);
        }
        System.out.println(cur.isWord);
        if(!cur.isWord){
            cur.isWord = true;
            size++;
        }
    }

    public boolean contains(String word){
        Node cur = root;
        for(int i=0;i<word.length();i++){
            char c =  word.charAt(i);
            if (cur.next.get(c)==null){
              return  false;
            }
            cur = cur.next.get(c);
        }

         return  cur.isWord;
    }

    public boolean isPrefix(String prefix){
        Node cur = root;
        for(int i=0;i<prefix.length();i++){
            char c = prefix.charAt(i);
            if(cur.next.get(c)==null){
                return false;
            }

            cur = cur.next.get(c);
        }
        return true;
    }
    public Integer getSize() {
        return size;
    }

    public static void main(String[] args) {
      Trie trie = new Trie();
        trie.add("panda");
        trie.add("pan");
        trie.add("bingo");
        trie.add("hello");
        trie.add("word");
        trie.add("words");
        trie.add("fang");
        trie.add("p");
        System.out.println("pan   "+trie.isPrefix("pan"));
    }
}
